package com.medical.guide.service.impl;

import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.medical.guide.mapper.DiseaseMapper;
import com.medical.domain.Disease;
import com.medical.guide.service.IDiseaseService;

/**
 * 常见病Service业务层处理
 * 
 * @author medical
 * @date 2024-07-19
 */
@Service
public class DiseaseServiceImpl implements IDiseaseService 
{
    @Autowired
    private DiseaseMapper diseaseMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 查询常见病
     * 
     * @param diseaseId 常见病主键
     * @return 常见病
     */
    @Override
    public Disease selectDiseaseByDiseaseId(Long diseaseId)
    {
        return diseaseMapper.selectDiseaseByDiseaseId(diseaseId);
    }

    /**
     * 查询常见病列表
     * 
     * @param disease 常见病
     * @return 常见病
     */
    @Override
    public List<Disease> selectDiseaseList(Disease disease)
    {
        return diseaseMapper.selectDiseaseList(disease);
    }

    /**
     * 新增常见病
     * 
     * @param disease 常见病
     * @return 结果
     */
    @Override
    public int insertDisease(Disease disease)
    {
        return diseaseMapper.insertDisease(disease);
    }

    /**
     * 修改常见病
     * 
     * @param disease 常见病
     * @return 结果
     */
    @Override
    public int updateDisease(Disease disease)
    {
        return diseaseMapper.updateDisease(disease);
    }

    /**
     * 批量删除常见病
     * 
     * @param diseaseIds 需要删除的常见病主键
     * @return 结果
     */
    @Override
    public int deleteDiseaseByDiseaseIds(Long[] diseaseIds)
    {
        return diseaseMapper.deleteDiseaseByDiseaseIds(diseaseIds);
    }

    /**
     * 删除常见病信息
     * 
     * @param diseaseId 常见病主键
     * @return 结果
     */
    @Override
    public int deleteDiseaseByDiseaseId(Long diseaseId)
    {
        return diseaseMapper.deleteDiseaseByDiseaseId(diseaseId);
    }

    /**
     * 根据位置查询常见病
     * @param positionId
     * @return
     */
    @Override
    public List<Disease> selectPositionIdList(Long positionId) {
        //判断缓存是否存在
        if (redisTemplate.hasKey("diseases"+positionId)){
            List<String> range = redisTemplate.opsForList().range("diseases" + positionId, 0, -1);
            ArrayList<Disease> list = new ArrayList<>();
            for (String s : range) {
                Disease diseases = JSON.parseObject(s, Disease.class);
                list.add(diseases);
            }
            return list;
        }
        List<Disease> diseases = diseaseMapper.selectPositionIdList(positionId);
        for (Disease disease : diseases) {
            redisTemplate.opsForList().rightPush("diseases"+positionId, JSON.toJSONString(disease));
        }
        return diseases;
    }
}
